package com.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.UserAPI;
import com.bean.BaseController;
import com.bean.WeixinUser;
import com.service.UserService;
import com.utils.SysConf;
import com.utils.WeixinTools;

/**
 * Created by qiao on 2017/5/15.
 */
@Controller
public class HomeController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping("base")
    public String base(HttpServletRequest request, String state) {
        paymentCallback(request);
//        if (unRegister(request)) return Cons.REGISTER_PAGE;
        return "redirect:jianpay/goto.do?p=index";
    }


    @RequestMapping("home")
    public String index() {
        return "index";
    }

    private void paymentCallback(HttpServletRequest request) {
        paymentCallback_product(request);
    }

    private void paymentCallback_product(HttpServletRequest request) {
        String code = request.getParameter("code");
        String openId = request.getParameter("openid");
        System.out.println("==================================code:" + code);
        WeixinUser user = null;
        if (StringUtils.isNotBlank(openId) &&
                StringUtils.equals(SysConf.get("env.active"), "test")) {
            user = userService.getByWechatNo(openId);
            if (user != null) {
                setSessionUser(request, user);
            }
            return;
        }
        if (code != null) {
            String openid = null;
            String access_token = null;
            String result_str = WeixinTools.getAuthToken(code);
            System.out.println("getOpenIdByCode: " + result_str);
            if (result_str != null && result_str.contains("access_token")) {
                JSONObject obj = JSON.parseObject(result_str);
                if (obj.containsKey("openid")) {
                    openid = obj.getString("openid");
                    access_token = obj.getString("access_token");
                }
                user = UserAPI.userInfo(access_token, openid);
                if(StringUtils.isBlank(user.getOpenid())) user.setOpenid(openid);
                System.out.println("userInfo: " + user);
                setSessionUser(request, user);
            }
        }
    }
}
